﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using System.Dynamic;
using KingRoad.EPM.PersonnelLogEntity.Model;

namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmTurnoverController : BaseController
    {
        /// <summary>
        /// 人员变动申报
        /// </summary>
        /// <returns></returns>
        public ActionResult TurnoverList(string pageName)
        {
            var model = new PlmTurnoverViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            model.ThePlmTurnoverInfoList = PlmTurnoverUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "T_timestamp", out totalRecord, " T_SectionName in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ")");
            //List<PlmTurnoverInfo> turnoverList = PlmTurnoverUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "T_DeclarationDate", out totalRecord, "");
            foreach (var item in model.ThePlmTurnoverInfoList)
            {
                var type = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Type));
                item.T_Type = type.Scd_Name;
                var position = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Position));
                item.T_Position = position.Scd_Name;
            }
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            model.TheUnitList = GetUnitListByType(0);

            return String.IsNullOrEmpty(pageName) ? View(model) : View(pageName, model);
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(PlmTurnoverViewModel vm)
        {

            var model = new PlmTurnoverViewModel();


            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);

            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return TurnoverList("TurnoverList");


            ViewBag.Sname = Request.Form["Sname"];
            ViewBag.reporttime = Request.Form["reporttime"];
            ViewBag.sectionname = Request.Form["sectionname"];
            ViewBag.positionname = Request.Form["positionname"];

            string sql = " T_SectionName in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";

            if (!string.IsNullOrEmpty(ViewBag.sectionname))
                sql += " and T_SectionName like  '%" + ViewBag.sectionname + "%' ";
            if (!string.IsNullOrEmpty(ViewBag.positionname))
                sql += " and T_Position in (select scd_id from Scm_SafetyConstructionDic where scd_name like '%" + ViewBag.positionname + "%' ) ";

            if (ViewBag.reporttime != "")
                sql += " and T_DeclarationDate = '" + ViewBag.reporttime + "' ";
            if (!string.IsNullOrEmpty(ViewBag.Sname))
            {
                sql += "and T_ExistingStaff = '" + ViewBag.Sname + "' or T_ChangePersonnel = '" + ViewBag.Sname + "'  ";
            }

            //var turnover = PlmTurnoverUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "T_DeclarationDate", out totalRecord, sql);
            model.ThePlmTurnoverInfoList = PlmTurnoverUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "T_timestamp", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            foreach (var item in model.ThePlmTurnoverInfoList)
            {
                var type = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Type));
                item.T_Type = type.Scd_Name;
                var position = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Position));
                item.T_Position = position.Scd_Name;
            }
           
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            model.TheUnitList = GetUnitListByType(0);
            return View("TurnoverList", model);
        }
        /// <summary>
        /// 人员变动申报添加
        /// </summary>
        /// <returns></returns>
        public ActionResult TurnoverAdd(int numPerPage)
        {
            PlmTurnoverViewModel vm = new PlmTurnoverViewModel();
            vm.ThePlmTurnoverInfoInfo = new PlmTurnoverInfo();
            vm.ThePlmTurnoverInfoInfo.T_Applicant = GetLoginUserRealName;
            //附件
            var assisId = GenerateRandom();
            var assisIdRet = 0;
            CreateAssistId(PlmTurnoverUIRule, assisId, out assisIdRet);
            ViewBag.AssisId = assisIdRet;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.变动申报);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.变动申报;
            return View(vm);
        }
        /// <summary>
        ///人员变动申报-添加 
        /// 功能：执行添加操作
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public JsonResult TurnooverAddData(PlmTurnoverViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.ThePlmTurnoverInfoInfo.T_ID = Guid.NewGuid().ToString();

                string section = Request.Form["section"];
                vm.ThePlmTurnoverInfoInfo.T_Position = Request.Form["position"];
                vm.ThePlmTurnoverInfoInfo.T_Type = Request.Form["changetype"];


                var nowpersonlist = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(Request.Form["nowname"]));
                vm.ThePlmTurnoverInfoInfo.T_ExistingStaff = nowpersonlist.Pi_Name;

                var changepersonList = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(Request.Form["changename"]));
                vm.ThePlmTurnoverInfoInfo.T_ChangePersonnel = changepersonList.Pi_Name;

                vm.ThePlmTurnoverInfoInfo.T_SectionName = section;
                var unitInfo = GetUnitInfoByCode(section);
                vm.ThePlmTurnoverInfoInfo.T_UnitID = Convert.ToInt32(unitInfo.UNIT_ID);
                vm.ThePlmTurnoverInfoInfo.T_UnitName = unitInfo.UNIT_NAME;

                vm.ThePlmTurnoverInfoInfo.T_State = "待审核";
                //TODO:登录人信息
                vm.ThePlmTurnoverInfoInfo.T_UserID = GetLoginUserId;//登录人ID
                vm.ThePlmTurnoverInfoInfo.T_UserName = GetLoginUserRealName;//登录人名称
                vm.ThePlmTurnoverInfoInfo.T_UpdateTime = DateTime.Now;

                vm.ThePlmTurnoverInfoInfo.T_ApprovalTime = DateTime.Now;
                var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                vm.ThePlmTurnoverInfoInfo.Assist_ID = AssistID;
                int safe = PlmTurnoverUIRule.AddPlmTurnoverInfo(vm.ThePlmTurnoverInfoInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "PersonnelLog.PlmTurnover.TurnoverList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 人员变动申报详情
        /// </summary>
        /// <returns></returns>
        public ActionResult TurnoverDetail(Guid id)
        {
            var turnoverLInfo = PlmTurnoverUIRule.GetPlmTurnoverInfoByID(id);
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.变动申报);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.变动申报;
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(turnoverLInfo.Assist_ID, "TurnOver_Rules");//TurnOver_Rules  BizType类型
            ViewBag.AssisId = turnoverLInfo.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            var type = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(turnoverLInfo.T_Type));
            turnoverLInfo.T_Type = type.Scd_Name;
            var position = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(turnoverLInfo.T_Position));
            turnoverLInfo.T_Position = position.Scd_Name;
            return View(new PlmTurnoverViewModel { ThePlmTurnoverInfoInfo = turnoverLInfo });
        }

        /// <summary>
        /// 人员变动申报-删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult TurnoverDelete(string id)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = PlmTurnoverUIRule.DeletePlmTurnoverInfo(id);
            });
            dynamic jsonReturn = new ExpandoObject();
            //删除成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "PersonnelLog.PlmTurnover.TurnoverList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 人员变动申报-批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SafeProductionMultiDelete()
        {
            dynamic jsonReturn = new ExpandoObject();
            var ids = base.GetRequestFormValue<string>("ids");
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = PlmTurnoverUIRule.DeletePlmTurnoverInfoMulti(ids);
            });

            //保存成功
            if (true)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "PersonnelLog.PlmTurnover.TurnoverList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 人员变动申报-编辑
        /// 说明：获取所需编辑的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult TurnoverEdit(Guid id)
        {
            var turnoverLInfo = PlmTurnoverUIRule.GetPlmTurnoverInfoByID(id);
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.变动申报);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.变动申报;
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(turnoverLInfo.Assist_ID, "TurnOver_Rules");//TurnOver_Rules  BizType类型
            ViewBag.AssisId = turnoverLInfo.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            return View(new PlmTurnoverViewModel { ThePlmTurnoverInfoInfo = turnoverLInfo });
        }
        /// <summary>
        /// 人员变动申报-保存编辑后数据
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public JsonResult TurnoverEditData(PlmTurnoverViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {

                var entity = PlmTurnoverUIRule.GetPlmTurnoverInfoByID(Guid.Parse(vm.ThePlmTurnoverInfoInfo.T_ID));
                string section = Request.Form["section"];
                entity.T_Position = Request.Form["position"];
                entity.T_Type = Request.Form["changetype"];


                var nowpersonlist = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(Request.Form["nowname"]));
                entity.T_ExistingStaff = nowpersonlist.Pi_Name;

                var changepersonList = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(Request.Form["changename"]));
                entity.T_ChangePersonnel = changepersonList.Pi_Name;
                entity.T_SectionName = section;
                var unitInfo = GetUnitInfoByCode(section);
                entity.T_UnitID = Convert.ToInt32(unitInfo.UNIT_ID);
                entity.T_UnitName = unitInfo.UNIT_NAME;
                entity.T_NowProfessional = vm.ThePlmTurnoverInfoInfo.T_NowProfessional;
                entity.T_ChangeProfessional = vm.ThePlmTurnoverInfoInfo.T_ChangeProfessional;
                entity.T_NowLicenseNum = vm.ThePlmTurnoverInfoInfo.T_NowLicenseNum;
                entity.T_ChangeLicenseNum = vm.ThePlmTurnoverInfoInfo.T_ChangeLicenseNum;
                entity.T_Reason = vm.ThePlmTurnoverInfoInfo.T_Reason;
                entity.T_DeclarationDate = vm.ThePlmTurnoverInfoInfo.T_DeclarationDate;
                entity.T_UpdateTime = DateTime.Now;

                entity.T_UserID = GetLoginUserId;
                entity.T_UserName = GetLoginUserRealName;

                var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                entity.Assist_ID = AssistID;
                int safe = PlmTurnoverUIRule.UpdatePlmTurnoverInfo(entity);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "更新成功",
                    navTabId = "PersonnelLog.PlmTurnover.TurnoverList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "更新失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 获取标段信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetSection()
        {
            var list = GetUnitListByType(0);
            return Json(list, JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 获取标段名称
        /// </summary>
        /// <param name="id">标段ID</param>
        /// <returns></returns>
        public JsonResult getSectionName(string code)
        {
            var list = GetUnitInfoByCode(code);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取职位信息
        /// </summary>
        /// <param name="id">标段ID</param>
        /// <returns></returns>
        public JsonResult GetPositionBySectionID(string code)
        {
            string parentID = "";
            if (code.Contains("JC"))
            {
                //检测单位职位
                parentID = "4AF2BCB9-D68B-4375-A770-9F6C85325C14";
            }
            else if (code.Contains("ZJ"))
            {
                //获取总监办职位
                parentID = "4AF2BCB9-D68B-4375-A770-9F6C85325C15";
            }
            else
            {   //获取驻地办职位
                parentID = "4AF2BCB9-D68B-4375-A770-9F6C85325C16";
            }
            var list = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID(parentID);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        ///  获取该标段下人员信息
        /// </summary>
        /// <param name="id">标段ID</param>
        /// <returns></returns>
        public JsonResult GetNameBySection(string code)
        {
            var list = PlmPersonnelinfoUIRule.GetPersonlInfoBySectionName(code);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取该标段职位下的人员姓名
        /// </summary>
        /// <param name="sectionid">标段ID</param>
        /// <param name="positionid">职位ID</param>     
        /// <returns></returns>
        public JsonResult GetNameByPositionID(string section, string positionid)
        {
            if (positionid.Length > 30)
            {
                positionid = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(positionid)).Scd_Name;
            }
            var list = PlmPersonnelinfoUIRule.GetAllPersonnelinfo("Pi_SectionName='" + section + "' and Pi_Post='" + positionid + "'");
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        //
        /// <summary>
        /// 获取该人员
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        public JsonResult GetPersonnelByID(string id)
        {
            var list = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(id));
            List<PlmPersonnelinfoInfo> tempList = new List<PlmPersonnelinfoInfo> { list };
            return Json(tempList, JsonRequestBehavior.AllowGet);
        }

    }
}
